﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace MsDbToSql
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }
        /// <summary>
        /// master数据库操作对象
        /// </summary>
        DbOprator masterDbo;
        /// <summary>
        /// 数据库操作对象
        /// </summary>
        DbOprator dbo;

        /// <summary>
        /// 数据库列表是否可用
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtServer_TextChanged(object sender, EventArgs e)
        {
            if (txtServer.Text.Trim().Length == 0 || txtUserName.Text.Trim().Length == 0
                || txtPwd.Text.Trim().Length == 0)
            {
                cboDataBase.Items.Clear();
                cboDataBase.Text = "";
                cboDataBase.Enabled = false;
            }
            else
            {
                cboDataBase.Enabled = true;
            }
        }

        private void cboDataBase_SelectedIndexChanged(object sender, EventArgs e)
        {
            dbo = new DbOprator(txtServer.Text,txtUserName.Text,txtPwd.Text,cboDataBase.Text);
            List<string> tables = dbo.GetAllTables();
            ckLTables.Items.Clear();
            foreach(string tb in tables)
            {
                ckLTables.Items.Add(tb);
            }
            //控制按钮可用状态
            if (ckLTables.Items.Count>0)
            {
                btnGenerateTable.Enabled = true;
                btnGenerateInsert.Enabled = true;
                btnTableAndInsert.Enabled = true;
                ckbAll.Enabled = true;
            }
            else
            {
                btnGenerateTable.Enabled = false;
                btnGenerateInsert.Enabled = false;
                btnTableAndInsert.Enabled = false;
                ckbAll.Enabled = false;
            }
        }
        

        private void cboDataBase_Enter(object sender, EventArgs e)
        {
            if (cboDataBase.Items.Count > 0) //如果已经加载数据库，则退出
                return;
            if (txtServer.Text.Trim().Length > 0 && txtUserName.Text.Trim().Length > 0
                && txtPwd.Text.Trim().Length > 0)
            {
                //检查服务器连接是否正确
                masterDbo = new DbOprator(txtServer.Text, txtUserName.Text, txtPwd.Text);
                if (masterDbo.CheckLink())  //如果正确
                {
                    //加载服务器上的所有数据库
                    List<string> dbs = masterDbo.GetAllDataBase();
                    cboDataBase.Items.Clear();
                    foreach (string db in dbs)
                    {
                        cboDataBase.Items.Add(db);
                    }
                }
                else
                {
                    //连接错误
                    MessageBox.Show("服务器连接不正确，请检查","错误",MessageBoxButtons.OK,MessageBoxIcon.Error);
                }
            }
        }

        /// <summary>
        /// 全选
        /// </summary>
        private void ckbAll_CheckedChanged(object sender, EventArgs e)
        {
            if (ckLTables.Items.Count > 0)
            {
                for (int i = 0; i < ckLTables.Items.Count; i++)
                {
                    ckLTables.SetItemChecked(i, ckbAll.Checked);
                }
            }
        }

        private void btnGenerateTable_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            //循环选中的项（表）,生成create table语句
            for(int i=0;i<ckLTables.Items.Count;i++)
            {
                if (ckLTables.GetItemCheckState(i)==CheckState.Checked)
                {
                    string tableName = ckLTables.GetItemText(ckLTables.Items[i]);
                    sb.AppendLine(dbo.CreateTable(tableName));
                }
            }
            //循环生成约束语句
            for (int i = 0; i < ckLTables.Items.Count; i++)
            {
                if (ckLTables.GetItemCheckState(i) == CheckState.Checked)
                {
                    string tableName = ckLTables.GetItemText(ckLTables.Items[i]);
                    sb.AppendLine(dbo.CreateConstrain(tableName));
                }
            }
            string txt = sb.ToString();
            SaveFile(txt);
           
        }

        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="txt"></param>
        private void SaveFile(string txt)
        {
            if (txt.Length > 0)
            {
                SaveFileDialog dialog = new SaveFileDialog();
                dialog.Filter = "SQL脚本(*.sql)|*.sql|文本(*.txt)|*.txt|所有文件(*.*)|*.*";
                if (DialogResult.OK == dialog.ShowDialog(this))
                {
                    using (StreamWriter sw = new StreamWriter(dialog.FileName, false, Encoding.Default))
                    {
                        sw.Write(txt);
                        DialogResult result= MessageBox.Show("SQL语句生成并保存成功！\n是否用记事本打开生成的文件？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        if (result==DialogResult.Yes)
                        {
                            //用记事本打开文件
                        }
                    }

                }
            }
            else
            {
                MessageBox.Show("没有被选中的表！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void btnGenerateInsert_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            //循环选中的项（表）
            for (int i = 0; i < ckLTables.Items.Count; i++)
            {
                if (ckLTables.GetItemCheckState(i) == CheckState.Checked)
                {
                    string tableName = ckLTables.GetItemText(ckLTables.Items[i]);
                    sb.AppendLine(dbo.GenerateInsert(tableName));
                }
            }
            string txt = sb.ToString();
            SaveFile(txt);
        }

        private void btnTableAndInsert_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            //防止出现外键冲突，先生成创建表的语句
            for (int i = 0; i < ckLTables.Items.Count; i++)
            {
                if (ckLTables.GetItemCheckState(i) == CheckState.Checked)
                {
                    string tableName = ckLTables.GetItemText(ckLTables.Items[i]);
                    sb.AppendLine(dbo.CreateTable(tableName));
                }
            }
            //循环生成约束语句
            for (int i = 0; i < ckLTables.Items.Count; i++)
            {
                if (ckLTables.GetItemCheckState(i) == CheckState.Checked)
                {
                    string tableName = ckLTables.GetItemText(ckLTables.Items[i]);
                    sb.AppendLine(dbo.CreateConstrain(tableName));
                }
            }
            //insert 语句
            for (int i = 0; i < ckLTables.Items.Count; i++)
            {
                if (ckLTables.GetItemCheckState(i) == CheckState.Checked)
                {
                    string tableName = ckLTables.GetItemText(ckLTables.Items[i]);
                    sb.AppendLine(dbo.GenerateInsert(tableName));
                }
            }
            string txt = sb.ToString();
            SaveFile(txt);
        }

        private void btnEntity_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            if (DialogResult.OK == dialog.ShowDialog())
            {
                TableToEntity ttn = new TableToEntity(dbo);
                for (int i = 0; i < ckLTables.Items.Count; i++)
                {
                    if (ckLTables.GetItemCheckState(i) == CheckState.Checked)
                    {
                        ttn.SaveFiles(ckLTables.GetItemText(ckLTables.Items[i]),dialog.SelectedPath);
                    }
                }
                DialogResult result = MessageBox.Show("实体类生成并保存成功！\n是否查看生成的文件？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result == DialogResult.Yes)
                {
                    //用记事本打开文件
                }
            }
        }
    }
}
